﻿#
Set-Location ${PSScriptRoot}

if ( ($IsWindows -eq $True) -or ($PSVersionTable.psversion.major -lt 6) ) #win
{
	Set-Location './win'
}

if ($IsLinux -eq $True)
{
	Set-Location './linux'
}

Add-Type -Path ".\Microsoft.AspNetCore.dll"
Set-Location ..


class PowerShellDelegate
{
	[string] $_script

	[string] $_pagefile

	PowerShellDelegate([string]$script,[string]$pagefile1)
	{
		$this._script = $script
		$this._pagefile = "${PSScriptRoot}/${pagefile1}"
	}

	[System.Threading.Tasks.Task] Invoke($context)
	{
		$powershell = [PowerShell]::Create()
		try
		{
			$powershell.AddScript($this._script).
			AddParameter("HttpContext", $context).
			AddParameter("pagefile2", $this._pagefile)
			$powerShell.Invoke()
		}
		finally
		{
			$powerShell.Dispose()
		}

		return [System.Threading.Tasks.Task]::CompletedTask
	}
}


#---------------------------------------------------------------------
#$p = Resolve-Path "${PSScriptRoot}\index.html"
$pindex = Get-Content -Path "${PSScriptRoot}\index.html" -Raw
#---------------------------------------------------------------------
$主页代码 = {
	param($HttpContext,$pagefile2)
	$pindex = Get-Content -Path $pagefile2 -Raw
	$a = [System.Text.Encoding]::UTF8.GetBytes($pindex)
	$HttpContext.Response.Body.WriteAsync($a, 0, $a.Length).AsTask().Wait()
}
$主页委托 = [powerShellDelegate]::new($主页代码,'index.html')

#---------------------------------------------------------------------
$获取时间代码 = {
	param($HttpContext)
	$a = Get-Date -Format F
	$b = [System.Text.Encoding]::GetEncoding(936).GetBytes($a)
	$HttpContext.Response.Body.WriteAsync($b, 0, $b.Length).AsTask().Wait()
}
$获取时间委托 = [powerShellDelegate]::new($获取时间代码,'')

#---------------------------------------------------------------------
# $env:ASPNETCORE_URLS = 'http://0.0.0.0:80'
$App = [Microsoft.AspNetCore.Builder.WebApplication]::Create()
[Void][Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions]::UseRouting($App)
[Void][Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions]::UseEndpoints($App, { [Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions]::MapGet($args[0],"/", $主页委托.Invoke) })
[Void][Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions]::UseEndpoints($App, { [Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions]::MapPost($args[0],"/getdate/", $获取时间委托.Invoke) })
$App.Run()
# 默认监听 http://127.0.0.1:5000
#---------------------------------------------------------------------
